/**
 * @param {string[]} words
 * @param {string} pattern
 * @return {string[]}
 */
export var findAndReplacePattern = function (words, pattern) {
  const ans = []
  for (const word of words) {
    if (checkWord(word, pattern)) {
      ans.push(word)
    }
  }
  return ans
}

function checkWord(word, pattern) {
  if (word.length !== pattern.length) return false
  const set = new Set()
  const map = new Map()
  for (let i = 0; i < pattern.length; i++) {
    const pChar = pattern[i]
    const wChar = word[i]
    if (map.has(pChar)) {
      if (map.get(pChar) !== wChar) return false
    } else if (!set.has(wChar)) {
      map.set(pChar, wChar)
      set.add(wChar)
    } else {
      return false
    }
  }
  return true
}

/**
 * @param {string[]} words
 * @param {string} pattern
 * @return {string[]}
 */
export var findAndReplacePattern2 = function (words, pattern) {
  const ans = []
  for (const word of words) {
    if (checkWord2(word, pattern) && checkWord2(pattern, word)) {
      ans.push(word)
    }
  }
  return ans
}

function checkWord2(word, pattern) {
  if (word.length !== pattern.length) return false
  const map = new Map()
  for (let i = 0; i < pattern.length; i++) {
    const pChar = pattern[i]
    const wChar = word[i]
    if (map.has(pChar)) {
      if (map.get(pChar) !== wChar) return false
    } else {
      map.set(pChar, wChar)
    }
  }
  return true
}
